package com.itheima.stock.service.impl;

import com.google.common.collect.Lists;
import com.itheima.stock.common.domain.StockInfoConfig;
import com.itheima.stock.common.domain.TaskThreadPoolInfo;
import com.itheima.stock.config.TaskExecutePool;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockBlockRtInfo;
import com.itheima.stock.pojo.StockMarketIndexInfo;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.service.StockTimerTaskService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.utils.ParserStockInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service("stockTimerTaskService")
@Slf4j
public class StockTimerTaskServiceImpl implements StockTimerTaskService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StockInfoConfig stockInfoConfig;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private ParserStockInfoUtil parserStockInfoUtil;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void getInnerMarketInfo() {
        //组装url
        //http://hq.sinajs.cn/list=s_sh000001,s_sz399001
        //marketUrl: http://hq.sinajs.cn/list=
        String url = stockInfoConfig.getMarketUrl() + String.join(",", stockInfoConfig.getInner());
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer", "https://finance.sina.com.cn/stock/");
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        //发请求
        String result = restTemplate.postForObject(url, new HttpEntity<>(headers), String.class);
        //正则
        String reg="var hq_str_(.+)=\"(.+)\";";//var hq_str_s_sh000001="上证指数,3094.668,-128.073,-3.97,436653,5458126";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(result);
        ArrayList<StockMarketIndexInfo> list = new ArrayList<>();
        while (matcher.find()){
            //获得大盘id
            String stockId = matcher.group(1);
            System.out.println("stockId = " + stockId);
            //其他信息按照逗号切割  上证指数,3094.668,-128.073,-3.97,436653,5458126 数据含义----------->指数名称,当前点数,当前价格,涨跌率,成交量（手）,成交额（万元）;
            String data = matcher.group(2);
            String[] split = data.split(",");
            String markName = split[0];
            BigDecimal curPoint=new BigDecimal(split[1]);
            BigDecimal curPrice=new BigDecimal(split[2]);
            BigDecimal upDownRate=new BigDecimal(split[3]);
            Long tradeAccount = Long.valueOf(split[4]);
            Long tradeVolume = Long.valueOf(split[5]);
            Date date = DateTimeUtil.getDateTimeWithoutSecond(DateTime.now()).toDate();
            //封装对象
            StockMarketIndexInfo stockMarketIndexInfo = StockMarketIndexInfo.builder().id(idWorker.nextId()+"")
                    .markName(markName)
                    .tradeVolume(tradeVolume)
                    .tradeAccount(tradeAccount)
                    .updownRate(upDownRate)
                    .curTime(date)
                    .curPoint(curPoint)
                    .currentPrice(curPrice)
                    .markId(stockId)
                    .build();
            list.add(stockMarketIndexInfo);

        }
        log.info("集合长度：{}，内容：{}",list.size(),list);
        //批量插入
        if (CollectionUtils.isEmpty(list)) {
            log.info("");
            return;
        }
        String curTime = DateTime.now().toString(DateTimeFormat.forPattern("yyyyMMddHHmmss"));
        log.info("采集的大盘数据：{},当前时间：{}",list,curTime);
        int i = stockMarketIndexInfoMapper.insertBatch(list);
        System.out.println("插入了"+i+"条数据");

    }

    @Override
    public void getstock() {
        //组装url
        //从数据库得到股票代码集合
        List<String> stockCodeList = stockBusinessMapper.getStockCode();
        //修改一下id 符合格式
        List<String> list = stockCodeList.stream().map(id -> {
            if (id.startsWith("6")) {
                id = "sh" + id;
            } else {
                id = "sz" + id;
            }
            return id;
        }).collect(Collectors.toList());
        //组装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        //分片
        List<List<String>> lists = Lists.partition(list, 20);
        //拼接url地址
        lists.forEach(codeList->{
            threadPoolTaskExecutor.execute(()->{
                String url = stockInfoConfig.getMarketUrl()+String.join(",",codeList);
                //发送请求
                String result = restTemplate.postForObject(url, new HttpEntity<>(headers), String.class);
                //解析 并 封装
                List<StockRtInfo> infos = parserStockInfoUtil.parser4StockOrMarketInfo(result, 3);
                log.info("数据量：{}",infos.size());
                //批量插入
                stockRtInfoMapper.insertBatch(infos);
            });
        });
    }

    @Override
    public void getblock() {
        //拼接url
        String url = stockInfoConfig.getBlockUrl();
        //发送请求
        String result = restTemplate.getForObject(url, String.class);
        //解析
        List<StockBlockRtInfo> stockBlockRtInfos = parserStockInfoUtil.parse4StockBlock(result);
        log.info("板块数据量：{}",stockBlockRtInfos.size());
        //分片插入
        List<List<StockBlockRtInfo>> list = Lists.partition(stockBlockRtInfos, 20);
        list.forEach(blockList->{
            threadPoolTaskExecutor.execute(()->{
                int count = stockBlockRtInfoMapper.insertBatch(blockList);
            });
        });
    }
}
